﻿using System.Data;
using System.Linq;
using smp.QueryDb.Structure;

namespace smp.QueryDb.Executing
{
    public class Execute
    {
        private readonly Command _command;
        protected readonly Procedure Procedure;

        public Execute(Procedure procedure)
        {
            if (procedure == null)
            {
                throw Helper.Error("Null Procedure is invalid for Execute initialisation");
            }
            Procedure = procedure;
            _command = new Command();
            _command.CommandBuilder.Append(procedure.Declaration);
        }

        internal ICommand Command { get { return _command; } }

        public IExecuteSet Set(ProcedureParameter parameter)
        {
            if (_command.Parameters.ToList().Find(x => x.Name == parameter.Name) != null)
            {
                throw Helper.Error("Invalid Set called on Execute {0}, cannot assign a parameter value twice to {1}",
                                   Procedure.Declaration,
                                   parameter.Name);
            }
            return new ExecuteSet(this, parameter);
        }

        internal void AddParameter(string name, DbType dataType, ParameterDirection direction, object value)
        {
            _command.AddParameter(new Parameter(name, dataType, value, direction));
        }
    }
}